package net.mihome.app.ui;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import net.mihome.app.AppContext;
import net.mihome.app.AppException;
import net.mihome.app.AppManager;
import net.mihome.app.R;
import net.mihome.app.api.ApiClient;
import net.mihome.app.bean.MiHomeBean;
import net.mihome.app.common.UIHelper;
import net.mihome.app.common.UpdateManager;
import net.mihome.app.ui.view.MihomeBigPaperView;
import net.mihome.app.ui.view.MihomeDianpuView;
import net.mihome.app.ui.view.MihomeRssTypeView;
import net.mihome.app.ui.view.MihomeZixunTypeView;
import net.mihome.app.ui.view.MyViewLinster;
import net.mihome.app.widget.BadgeView;
import net.mihome.app.widget.LoadingDialog;
import net.mihome.app.widget.ScrollLayout;

import java.util.ArrayList;
import java.util.List;

import greendroid.widget.MyQuickAction;
import greendroid.widget.QuickActionGrid;
import greendroid.widget.QuickActionWidget;
import greendroid.widget.QuickActionWidget.OnQuickActionClickListener;

/**
 * 应用程序首页
 * 
 * @author liux (http://my.oschina.net/liux)
 * @version 1.0
 * @created 2012-3-21
 */
public class Main extends BaseActivity {
	//
	View jiaodianView;
	//
	private Handler handler;
	//
	public static final int QUICKACTION_LOGIN_OR_LOGOUT = 0;
	public static final int QUICKACTION_USERINFO = 1;
	public static final int QUICKACTION_SOFTWARE = 2;
	public static final int QUICKACTION_SEARCH = 3;
	public static final int QUICKACTION_SETTING = 2;
	public static final int QUICKACTION_EXIT = 3;
	private ScrollLayout mScrollLayout;
	private RadioButton[] mButtons;
	private String[] mHeadTitles;
	private int mViewCount;
	private int mCurSel;

	private ImageView mHeadLogo;
	private TextView mHeadTitle;
	private ImageButton mHead_search;
	private Button mHeadPub_post;
	private View dazibaoMyButton ;
	private View mHeadPub_tweet;
	private View mHeadPub_talk;
	private View baoxiuAddButton;


	//米生活view
	private MihomeZixunTypeView zixunListView;
	private View zixunView;
	//当前米生活标签页
	//
	private MihomeRssTypeView redianxinwenListView2;
	//
	private MihomeBigPaperView linliquanListView;
	private MihomeDianpuView dianpuGridView;
	private View redianxinwenView;
	//九宫格

	/**
	 * 米生活view适配器
	 * */

	
	private RadioButton fbNews;
	private RadioButton fbQuestion;
	private RadioButton fbTweet;
	private RadioButton fbactive;
	private ImageView fbSetting;
	//米生活
	private Button framebtn_mihome_zixun;
	private Button framebtn_mihome_redianxinwen;
	private Button framebtn_mihome_dianpu;
	private Button framebtn_mihome_linliquan;
	
	private View rssAddButton;
	//米宅服务
	
	private Button framebtn_Active_atme;
	private Button framebtn_Active_comment;
	private Button framebtn_Active_message;



	public static BadgeView bv_active;
	public static BadgeView bv_message;
	public static BadgeView bv_atme;
	public static BadgeView bv_review;
	
	public View layout;
	
	private QuickActionWidget mGrid;// 快捷栏控件


	private AppContext appContext;// 全局Context
	
	private DoubleClickExitHelper mDoubleClickExitHelper;
	
	public final static int PROGRESS_START=0;

	public final static int PROGRESS_STOP=1;
	public enum ActivityPoint{
		ZIXUN,REDIANXINWEN,DIANPU,LINLIQUAN
	}
	private LoadingDialog progressDialog;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mDoubleClickExitHelper = new DoubleClickExitHelper(this);
		appContext = (AppContext) getApplication();
		//初始化头部view
		this.initHeadView();
		//初始化底部view
		this.initFootBar();
		//初始化页面滑动view
		this.initPageScroll();
		//初始化frame button
		this.initFrameButton();
		
		this.initBadgeView();
		
		this.initQuickActionGrid();
		//初始化所有list数据
		this.initFrameListView();
		// 检查新版本
		if (appContext.isCheckUp()) {
			UpdateManager.getUpdateManager().checkAppUpdate(this, false);
		}

		// 启动轮询通知信息
//		this.foreachUserNotice();
		// 检查是否需要下载欢迎图片
		this.checkBackGround();
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mViewCount == 0)
			mViewCount = 4;
		if (mCurSel == 0 && !fbNews.isChecked()) {
			fbNews.setChecked(true);
			fbQuestion.setChecked(false);
			fbTweet.setChecked(false);
			fbactive.setChecked(false);
		}
		// 读取左右滑动配置
		mScrollLayout.setIsScroll(appContext.isScroll());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

	}

	/**
	 * 初始化快捷栏
	 */
	private void initQuickActionGrid() {
		mGrid = new QuickActionGrid(this);
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_login,
				R.string.main_menu_login));
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_myinfo,
				R.string.main_menu_myinfo));
//		mGrid.addQuickAction(new MyQuickAction(this,
//				R.drawable.ic_menu_software, R.string.main_menu_software));
//		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_sweep,
//				R.string.main_menu_sweep));
		mGrid.addQuickAction(new MyQuickAction(this,
				R.drawable.ic_menu_setting, R.string.main_menu_setting));
		mGrid.addQuickAction(new MyQuickAction(this, R.drawable.ic_menu_exit,
				R.string.main_menu_exit));

		mGrid.setOnQuickActionClickListener(mActionListener);
	}

	/**
	 * 快捷栏item点击事件
	 */
	private OnQuickActionClickListener mActionListener = new OnQuickActionClickListener() {
		public void onQuickActionClicked(QuickActionWidget widget, int position) {
			switch (position) {
			case QUICKACTION_LOGIN_OR_LOGOUT:// 用户登录-注销
				UIHelper.loginOrLogout(Main.this);
				checkLogin();
				break;
			case QUICKACTION_USERINFO:// 我的资料
				UIHelper.showUserInfo(Main.this);
				break;
//			case QUICKACTION_SOFTWARE:// 开源软件
//				UIHelper.showSoftware(Main.this);
//				break;
//			case QUICKACTION_SEARCH:// 
//				UIHelper.showCapture(Main.this);
//				break;
			case QUICKACTION_SETTING:// 设置
				UIHelper.showSetting(Main.this);
				break;
			case QUICKACTION_EXIT:// 退出
				AppManager.getAppManager().finishActivity(Main.this);
				break;
			}
		}
	};
	
	private void checkBackGround() {
		if (!appContext.isNetworkConnected()) {
			return;
		}
		// 启动线程去检查服务器接口是否需要下载新的欢迎界面背景图片到手机
		new Thread(){
			public void run() {
				// 将图片下载下来
				try {
					ApiClient.checkBackGround(appContext);
				} catch (AppException e) {
				}
			}
		}.start();
	}

	/**
	 * 初始化所有ListView
	 */
	private void initFrameListView() {
		if (progressDialog != null)
		{
			progressDialog.dismiss();
		}else{
			this.progressDialog=new LoadingDialog(this);
		}
		this.progressDialog.setContentView(R.layout.loadingdialog);
		handler=new Handler(new Handler.Callback() {
			
			@Override
			public boolean handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch (msg.what) {
				case PROGRESS_START:
//					Toast.makeText(Main.this,"开始加载", Toast.LENGTH_SHORT).show();
					progressDialog.show();
					break;

				case PROGRESS_STOP:
//					Toast.makeText(Main.this,"加载 结束", Toast.LENGTH_SHORT).show();
					progressDialog.dismiss();
					break;
				default:
					break;
				}
				return false;
			}
		}); 
		// 初始化listview控件
		this.initNewsListView();
		initRedianxinwenLv();
		this.initTweetListView();
		this.initActiveListView();
//		// 加载listview数据
	} 
	

	/**
	 * 初始化新闻列表
	 */
	private void initNewsListView() {
		zixunView=findViewById(R.id.include_zixun_main);
		zixunListView = (MihomeZixunTypeView) findViewById(R.id.frame_listview_news);
		zixunListView.initData();
	}
	
	/**
	 * 初始化热点新闻（新闻订阅）列表
	 * */
	public void initRedianxinwenLv(){
//		redianxinwenListView2=(MihomeRssTypeView) findViewById(R.id.rss_view);
//		redianxinwenListView2.initData();
		redianxinwenListView2.setMyViewLinster(new MyViewLinster() {
			
			@Override
			public void onLoadComplete() {
				handler.sendEmptyMessage(PROGRESS_STOP);
			}

			@Override
			public void onBeforeLoad() {
				handler.sendEmptyMessage(PROGRESS_START);
			}
		});
	}


	/**
	 * 初始化邻里圈
	 */
	private void initTweetListView() {
		linliquanListView = (MihomeBigPaperView) findViewById(R.id.dazibao_view);
		linliquanListView.setMyViewLinster(new MyViewLinster() {
			
			@Override
			public void onLoadComplete() {
				handler.sendEmptyMessage(PROGRESS_STOP);
			}

			@Override
			public void onBeforeLoad() {
				handler.sendEmptyMessage(PROGRESS_START);
			}
		});
//		linliquanListView.initData();
	}

	/**
	 * 初始化动态列表
	 */
	@SuppressLint("NewApi")
	private void initActiveListView() {
		dianpuGridView = (MihomeDianpuView) findViewById(R.id.frame_stageview_active);
//		dianpuGridView.initData();
		dianpuGridView.setMyViewLinster(new MyViewLinster() {
			
			@Override
			public void onLoadComplete() {
				handler.sendEmptyMessage(PROGRESS_STOP);
			}

			@Override
			public void onBeforeLoad() {
				handler.sendEmptyMessage(PROGRESS_START);
			}
		});
		}
		


	/**
	 * 初始化头部视图
	 */
	private void initHeadView() {
		mHeadLogo = (ImageView) findViewById(R.id.main_head_logo);
		mHeadTitle = (TextView) findViewById(R.id.main_head_title);
		mHead_search = (ImageButton) findViewById(R.id.main_head_search);
//		mHeadPub_post = (Button) findViewById(R.id.mihome_pub_talk);
		dazibaoMyButton= findViewById(R.id.mihome_pub_my2);
		dazibaoMyButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				UIHelper.showUserCenter(Main.this, appContext.getLoginInfo().getUid(),
						appContext.getLoginInfo().getName(),null);
			}
		});
		mHeadPub_tweet = findViewById(R.id.mihome_pub_dazibao2);
		mHeadPub_talk =  findViewById(R.id.mihome_pub_talk2);
		
		mHead_search.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				UIHelper.showSearch(v.getContext());
			}
		});
//		mHeadPub_post.setOnClickListener(new View.OnClickListener() {
//			public void onClick(View v) {
//				UIHelper.showQuestionPub(v.getContext());
//			}
//		});
		mHeadPub_talk.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
//				Intent intent=new Intent(Main.this,ChatActivity.class);
//				startActivity(intent);
				Intent intent=new Intent(Main.this,MihomeActivisActivity.class);
				startActivity(intent);
			}
		});
		mHeadPub_tweet.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				UIHelper.showTweetPub(Main.this);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==UIHelper.REQUEST_CODE_FOR_DAZIBAO_PUB){
			linliquanListView.initData(null);
		}
	}

	/**
	 * 初始化底部栏
	 */
	private void initFootBar() {
		fbNews = (RadioButton) findViewById(R.id.main_footbar_news);
		fbQuestion = (RadioButton) findViewById(R.id.main_footbar_question);
		fbTweet = (RadioButton) findViewById(R.id.main_footbar_tweet);
		fbactive = (RadioButton) findViewById(R.id.main_footbar_active);

		fbSetting = (ImageView) findViewById(R.id.main_footbar_setting);
		fbSetting.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				// 展示快捷栏&判断是否登录&是否加载文章图片
				UIHelper.showSettingLoginOrLogout(Main.this,
						mGrid.getQuickAction(0));
				mGrid.show(v);
			}
		});
	}

	/**
	 * 初始化通知信息标签控件
	 */
	private void initBadgeView() {
		bv_active = new BadgeView(this, fbactive);
		bv_active.setBackgroundResource(R.drawable.widget_count_bg);
		bv_active.setIncludeFontPadding(false);
		bv_active.setGravity(Gravity.CENTER);
		bv_active.setTextSize(8f);
		bv_active.setTextColor(Color.WHITE);

		bv_atme = new BadgeView(this, framebtn_Active_atme);
		bv_atme.setBackgroundResource(R.drawable.widget_count_bg);
		bv_atme.setIncludeFontPadding(false);
		bv_atme.setGravity(Gravity.CENTER);
		bv_atme.setTextSize(8f);
		bv_atme.setTextColor(Color.WHITE);

		bv_review = new BadgeView(this, framebtn_Active_comment);
		bv_review.setBackgroundResource(R.drawable.widget_count_bg);
		bv_review.setIncludeFontPadding(false);
		bv_review.setGravity(Gravity.CENTER);
		bv_review.setTextSize(8f);
		bv_review.setTextColor(Color.WHITE);

		bv_message = new BadgeView(this, framebtn_Active_message);
		bv_message.setBackgroundResource(R.drawable.widget_count_bg);
		bv_message.setIncludeFontPadding(false);
		bv_message.setGravity(Gravity.CENTER);
		bv_message.setTextSize(8f);
		bv_message.setTextColor(Color.WHITE);
	}

	/**
	 * 初始化水平滚动翻页
	 */
	private void initPageScroll() {
		mScrollLayout = (ScrollLayout) findViewById(R.id.main_scrolllayout);

		LinearLayout linearLayout = (LinearLayout) findViewById(R.id.main_linearlayout_footer);
		mHeadTitles = getResources().getStringArray(R.array.head_titles);
//		mViewCount = mScrollLayout.getChildCount();
		mViewCount =2;
		mButtons = new RadioButton[mViewCount];

		for (int i = 0; i < mViewCount; i++) {
			mButtons[i] = (RadioButton) linearLayout.getChildAt(i * 2);
			mButtons[i].setTag(i);
			mButtons[i].setChecked(false);
			mButtons[i].setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					int pos = (Integer) (v.getTag());
					// 点击当前项刷新
					if (mCurSel == pos) {
						switch (pos) {
						case 0:// 资讯+博客
//							if (zixunListView.getVisibility() == View.VISIBLE)
//								zixunListView.clickRefresh();
//							else
//								redianxinwenListView.clickRefresh();
							break;
						case 1:// 问答
//							lvQuestion.clickRefresh();
							break;
						case 2:// 动弹
//							linliquanListView.clickRefresh();
							break;
						case 3:// 动态+留言
//							if (dianpuGridView.getVisibility() == View.VISIBLE)
//								dianpuGridView.clickRefresh();
//							else
//								lvMsg.clickRefresh();
							break;
						}
					}
					mScrollLayout.snapToScreen(pos);
				}
			});
		}

		// 设置第一显示屏
		mCurSel = 0;
		mButtons[mCurSel].setChecked(true);

		mScrollLayout
				.SetOnViewChangeListener(new ScrollLayout.OnViewChangeListener() {
					public void OnViewChange(int viewIndex) {
						// 切换列表视图-如果列表数据为空：加载数据
						switch (viewIndex) {
						case 0:// 资讯
							if (zixunListView.getVisibility() == View.VISIBLE||zixunView.getVisibility()==View.VISIBLE) {
								zixunListView.initData();
							}
							break;
						case 1:// 米宅服务
							if (!appContext.checkLogin()) {
//								if (lvQuestion.getVisibility() == View.VISIBLE
//										&& lvQuestionData.isEmpty()) {
//									lvQuestion_foot_more
//											.setText(R.string.load_empty);
//									lvQuestion_foot_progress
//											.setVisibility(View.GONE);
//								} else if (lvMsg.getVisibility() == View.VISIBLE
//										&& lvMsgData.isEmpty()) {
//									lvMsg_foot_more
//											.setText(R.string.load_empty);
//									lvMsg_foot_progress
//											.setVisibility(View.GONE);
//								}
//								UIHelper.showLoginDialog(Main.this);
								Intent intent=new Intent(Main.this,LoginActivity.class);
								startActivity(intent);
								finish();
								break;
							}
							break;
						case 2:// 动弹
							break;
						case 3:// 动态
								// 判断登录
							if (!checkLogin()) {
								break;
							}
							break;
						}
					}
				});
	}


	/**
	 * 初始化各个主页的按钮(资讯、问答、动弹、动态、留言)
	 */
	private void initFrameButton() {
		// 初始化按钮控件 <米生活>
		framebtn_mihome_zixun = (Button) findViewById(R.id.frame_btn_mihome_zixun);
		framebtn_mihome_redianxinwen = (Button) findViewById(R.id.frame_btn_mihome_redianxinwen);
		framebtn_mihome_dianpu = (Button) findViewById(R.id.frame_btn_mihome_dianpu);
		framebtn_mihome_linliquan = (Button) findViewById(R.id.frame_btn_mihome_linliquan);
		layout=(View) findViewById(R.id.frame_listview_tweet_lay);
		redianxinwenView=findViewById(R.id.include_rss_main);
		framebtn_mihome_zixun.setEnabled(false);
		framebtn_mihome_redianxinwen.setEnabled(true);
		framebtn_mihome_dianpu.setEnabled(true);
		framebtn_mihome_linliquan.setEnabled(true);
		baoxiuAddButton= findViewById(R.id.mihome_pub_baoxiu);
		rssAddButton=findViewById(R.id.dingyue_add);
		baoxiuAddButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				UIHelper.showQuestionPub(arg0.getContext());
			}
		});
		rssAddButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				String rssCheckedString=appContext.getUserPropertie("rss_checked");
				List<String> list=new ArrayList<String>();
				if(rssCheckedString!=null){
					list=RssResourceActivity.string2list(rssCheckedString);
				}
				RssResourceActivity rssResourceActivity=new RssResourceActivity(Main.this,true,new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface arg0) {
						framebtn_mihome_redianxinwen.performClick();
					}
				},list);
				rssResourceActivity.show();
			}
		});
		//设置frame按钮事件
		framebtn_mihome_zixun.setOnClickListener(frameMihomeBtnClick(
				framebtn_mihome_zixun, MiHomeBean.MIHOME_TYPE_ZIXUN));
		
		framebtn_mihome_redianxinwen.setOnClickListener(frameMihomeBtnClick(
				framebtn_mihome_redianxinwen, MiHomeBean.MIHOME_TYPE_REDIANXINWEN));
		
		framebtn_mihome_dianpu.setOnClickListener(frameMihomeBtnClick(
				framebtn_mihome_dianpu, MiHomeBean.MIHOME_TYPE_DIANPU));
		
		framebtn_mihome_linliquan.setOnClickListener(frameMihomeBtnClick(
				framebtn_mihome_linliquan, MiHomeBean.MIHOME_TYPE_LINLIQUAN));
	}
	/**
	 * 米生活顶部按钮事件
	 * */
	private View.OnClickListener frameMihomeBtnClick(final Button btn,final int catalog) {
		return new View.OnClickListener() {
			public void onClick(View v) {
				if (btn == framebtn_mihome_zixun) {
					framebtn_mihome_zixun.setEnabled(false);
					zixunListView.setVisibility(View.VISIBLE);
					zixunView.setVisibility(View.VISIBLE);
				} else {
					framebtn_mihome_zixun.setEnabled(true);
					zixunListView.setVisibility(View.GONE);
					zixunView.setVisibility(View.GONE);
				}
				if (btn == framebtn_mihome_redianxinwen) {
					framebtn_mihome_redianxinwen.setEnabled(false);
					redianxinwenView.setVisibility(View.VISIBLE);
					redianxinwenListView2.initData();
				} else {
					framebtn_mihome_redianxinwen.setEnabled(true);
					redianxinwenView.setVisibility(View.GONE);
				}
				if (btn == framebtn_mihome_dianpu) {
					framebtn_mihome_dianpu.setEnabled(false);
					dianpuGridView.setVisibility(View.VISIBLE);
					dianpuGridView.initData();
				} else {
					framebtn_mihome_dianpu.setEnabled(true);
					dianpuGridView.setVisibility(View.GONE);
				}
				if (btn == framebtn_mihome_linliquan) {
					framebtn_mihome_linliquan.setEnabled(false);
					layout.setVisibility(View.VISIBLE);
					linliquanListView.initData(null);
				} else {
					layout.setVisibility(View.GONE);
					framebtn_mihome_linliquan.setEnabled(true);
				}
			}
		};
	}
	



	/**
	 * 创建menu TODO 停用原生菜单
	 */
	public boolean onCreateOptionsMenu(Menu menu) {
		return false;
	}

	/**
	 * 菜单被显示之前的事件
	 */
	public boolean onPrepareOptionsMenu(Menu menu) {
		UIHelper.showMenuLoginOrLogout(this, menu);
		return true;
	}

	/**
	 * 处理menu的事件
	 */
	public boolean onOptionsItemSelected(MenuItem item) {
		int item_id = item.getItemId();
		switch (item_id) {
		case R.id.main_menu_user:
			UIHelper.loginOrLogout(this);
			break;
		case R.id.main_menu_about:
			UIHelper.showAbout(this);
			break;
		case R.id.main_menu_setting:
			UIHelper.showSetting(this);
			break;
		case R.id.main_menu_exit:
			UIHelper.Exit(this);
			break;
		}
		return true;
	}

	/**
	 * 监听返回--是否退出程序
	 */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		boolean flag = true;
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 是否退出应用
			return mDoubleClickExitHelper.onKeyDown(keyCode, event);
		} else if (keyCode == KeyEvent.KEYCODE_MENU) {
			// 展示快捷栏&判断是否登录
			UIHelper.showSettingLoginOrLogout(Main.this,
					mGrid.getQuickAction(0));
			mGrid.show(fbSetting, true);
		} else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			// 展示搜索页
			UIHelper.showSearch(Main.this);
		} else {
			flag = super.onKeyDown(keyCode, event);
		}
		return flag;
	}
	/**
	 * 在一些重要的地方校验是否登录
	 * 主要就是校验是否有token
	 * */
	public boolean checkLogin(){
		if(!appContext.checkLogin()){
			Intent intent=new Intent(Main.this,LoginActivity.class);
			startActivity(intent);
			finish();
			return false;
		}else{
			return true;
		}
	}
	
}
